﻿/*
Copyright 2011 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 Authors:
 Nadim Ratani      (nratani@google.com)
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Newtonsoft.Json.Linq;

namespace Sample.Controllers
{
    /// <summary>
    /// The controller for the order page, where the user makes their initial
    /// order.
    /// </summary>
    public class OrderController : Controller
    {
        /// <summary>
        /// Creates a masked wallet request JWT for the Buy button.
        /// </summary>
        public ActionResult Index()
        {
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            TimeSpan diff = DateTime.UtcNow - origin;
            int iat = (int)Math.Floor(diff.TotalSeconds);

            JObject maskedWalletRequest = new JObject(
                new JProperty("iss", Config.iss),
                new JProperty("origin", Config.origin),
                new JProperty("aud", Config.aud),
                new JProperty("iat", iat),
                new JProperty("typ", "google/paymentexpress/v1/masked/request"),
                new JProperty("selectors", new JObject(
                    new JProperty("pay", new JObject(
                        new JProperty("type", "PAYMENT_INSTRUMENT")
                    )),
                    new JProperty("ship", new JObject(
                        new JProperty("type", "SHIPPING_ADDRESS")
                    ))
                ))
            );
            string maskedWalletRequestJWT = JWT.JsonWebToken.Encode(maskedWalletRequest, Config.signingKey, JWT.JwtHashAlgorithm.HS256);

            ViewData["maskedWalletRequestJWT"] = maskedWalletRequestJWT;
            return View();
        }
    }
}
